<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 警告区域 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 级联选择区域 -->
      <span>请选择商品分类：</span>
      <el-cascader
        clearable
        v-model="selectCate"
        :options="catelist"
        :props="cateProps"
        @change="parentCateChange"
      ></el-cascader>
      <!-- tabs区域 -->
      <el-tabs v-model="activeName" @tab-click="tabHandleClick">
        <!-- 用户管理页签 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 按钮区域 -->
          <el-button
            :disabled="selectCate.length !== 3"
            type="primary"
            size="mini"
            @click="addDialogVisible = true"
            >添加动态参数</el-button
          >
          <!-- 表格区域 -->
          <el-table :data="manyTableData" style="width: 100%" stripe border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="index"
                  v-for="(item, index) in scope.row.attr_vals"
                  closable
                  @close="handleClose(index, scope.row)"
                  type="danger"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ 新标签</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  icon="el-icon-edit"
                  type="primary"
                  @click="showEditDialog(scope.row)"
                  >修改</el-button
                >
                <el-button
                  size="mini"
                  icon="el-icon-delete"
                  type="danger"
                  @click="delParams(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 配置管理页签 -->
        <el-tab-pane label="静态配置" name="only">
          <!-- 按钮区域 -->
          <el-button
            :disabled="selectCate.length !== 3"
            type="primary"
            size="mini"
            @click="addDialogVisible = true"
            >添加静态配置</el-button
          >
          <!-- 表格区域 -->
          <el-table :data="onlyTableData" style="width: 100%" stripe border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="index"
                  v-for="(item, index) in scope.row.attr_vals"
                  closable
                  @close="handleClose(index, scope.row)"
                  type="danger"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ 新标签</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="属性名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  icon="el-icon-edit"
                  type="primary"
                  @click="showEditDialog(scope.row)"
                  >修改</el-button
                >
                <el-button
                  size="mini"
                  icon="el-icon-delete"
                  type="danger"
                  @click="delParams(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加动态参数和静态属性的对话框 -->
      <el-dialog
        :title="'添加' + titleText"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClosed"
      >
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="100px"
        >
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改动态参数和静态属性的对话框 -->
      <el-dialog
        :title="'修改' + titleText"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClosed"
      >
        <el-form
          :model="editForm"
          :rules="addFormRules"
          ref="editFormRef"
          label-width="100px"
        >
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 商品分类列表
      catelist: [],
      // 选中的级联选择器数组
      selectCate: [],
      // 商品级联选择器配置
      cateProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // 页签选中的子页面
      activeName: 'many',
      // 当前选中的三级分类的id
      cateId: null,
      // 动态参数列表
      manyTableData: [],
      // 静态配置列表
      onlyTableData: [],
      // 控制添加对话框的显隐
      addDialogVisible: false,
      // 控制修改对话框的显隐
      editDialogVisible: false,
      // 添加参数和属性的表单
      addForm: {
        attr_name: ''
      },
      // 修改参数和属性的表单
      editForm: {
        attr_name: ''
      },
      // 添加表单的验证规则对象
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 颜色数组
      tagColor: ['',
        'success',
        'info',
        'danger',
        'warning'
      ],
      // 颜色随机数
      colorRandom: Math.floor(Math.random() * (4 + 1))
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取商品列表
    async getCateList () {
      const { data: res } = await this.$http.get('/categories')
      if (res.meta.status !== 200) return this.$message.error('获取商品列表失败')
      // 把数据列表赋值给catelist
      this.catelist = res.data
      // console.log(this.catelist)
    },
    // 选择项变化触发的函数
    parentCateChange () {
      this.getParamsData()
    },
    // 获取参数列表
    async getParamsData () {
      // 如果选中的是一级或者二级分类
      if (this.selectCate.length < 3 && this.selectCate.length !== 0) {
        // 清空选中的级联选择器数组
        this.selectCate = []
        // 清空表格
        this.manyTableData = []
        this.onlyTableData = []
        // 清空当前id
        this.cateId = null
        this.$message.warning('只允许为第三级分类设置相关参数！')
      } else if (this.selectCate.length === 3) {
        // 为当前选中的id赋值
        this.cateId = this.selectCate[this.selectCate.length - 1]
        // 通过所选三级分类id与当前所处面板请求参数
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: this.activeName
          }
        })
        if (res.meta.status !== 200) return this.$message.error('获取参数列表失败')
        res.data.forEach(item => {
          // 字符串变成数组
          if (item.attr_write === 'list') {
            item.attr_vals = !item.attr_vals ? [] : item.attr_vals.split(',')
          } else {
            item.attr_vals = !item.attr_vals ? [] : item.attr_vals.split(' ')
          }
          // 控制文本框的显示与隐藏
          item.inputVisible = false
          // 文本框中输入的值
          item.inputValue = ''
        })
        // console.log(res.data)
        if (this.activeName === 'many') {
          this.manyTableData = res.data
        } else {
          this.onlyTableData = res.data
        }
      }
      // console.log(this.selectCate)
    },
    // 页签被点击时
    tabHandleClick () {
      this.getParamsData()
    },
    // 添加对话框的关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 修改对话框的关闭事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 添加参数确定按钮
    addParams () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`/categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        // console.log(res)
        if (res.meta.status !== 201) return this.$message.error(`添加${this.titleText}失败`)
        this.$message.success(`添加${this.titleText}成功`)
        // 更新数据
        this.getParamsData()
        // 关闭对话框
        this.addDialogVisible = false
      })
    },
    // 修改参数确定按钮
    editParams () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        // console.log(this.editForm)
        const { data: res } = await this.$http.put(`categories/${this.editForm.cat_id}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        })
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error(`修改${this.titleText}失败`)
        this.$message.success(`修改${this.titleText}成功`)
        // 更新数据
        this.getParamsData()
        // 隐藏对话框
        this.editDialogVisible = false
      })
    },
    // 删除参数
    async delParams (info) {
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // console.log(info)
        const { data: res } = await this.$http.delete(`categories/${info.cat_id}/attributes/${info.attr_id}`)
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error(`删除${this.titleText}失败`)
        this.$message.success(`删除${this.titleText}成功`)
        // 更新数据
        this.getParamsData()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 显示修改参数对话框
    showEditDialog (info) {
      this.editDialogVisible = true
      this.editForm.attr_name = info.attr_name
      this.editForm.attr_id = info.attr_id
      this.editForm.cat_id = info.cat_id
      // console.log(info)
      // console.log(this.editForm)
    },
    // 序列化attr_val数组
    serializationString (str) {
      return str.split(' ')
    },
    // 显示动态tag编辑中的input
    showInput (row) {
      row.inputVisible = true
      // 文本框自动获得焦点
      this.$nextTick(_ => {
        // $nextTick的作用：当页面上的元素被重新渲染之后，才会指定回调函数中的代码
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 动态标签中的input确定输入（按下回车，失去焦点）
    async handleInputConfirm (row) {
      // 字符串两端的空格去掉后长度为0，说明是不合法字符
      if (row.inputValue.trim().length === 0) {
        // 重置字符
        row.inputValue = ''
        // 隐藏输入框
        row.inputVisible = false
      } else {
        // console.log(row)
        row.attr_vals.push(row.inputValue.trim())
        row.inputVisible = false
        row.inputValue = ''
        this.saveAttrVals(row)
      }
    },
    // 保存attr_vals到数据库
    async saveAttrVals (row) {
      const { data: res } = await this.$http.put(`categories/${row.cat_id}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_write === 'list' ? row.attr_vals.join(',') : row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('修改参数项失败')
      this.$message.success('修改参数项成功！')
    },
    // 点击关闭动态标签,删除对应的选项
    handleClose (index, row) {
      row.attr_vals.splice(index, 1)
      this.saveAttrVals(row)
    }
  },
  computed: {
    // 动态标题
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>
<style lang="less" scoped>
.el-alert {
  margin-bottom: 15px;
}
.el-cascader {
  width: 35%;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
